package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginCheckinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();//backend/index.html
        log.info("拦截到请求: {}",requestURI);

        //判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if(empId != null){

            //用户已登录
            BaseContext.setCurrentId(empId);
            //放行
            return  true;
        }

        //判断移动端用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        if(userId != null){

            //用户已登录
            BaseContext.setCurrentId(userId);
            //放行
            return  true;
        }


        //用户未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
